import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from "../components/Login"
// import Home from "../components/Home"

//懒加载 原理为函数点击在执行return回来
const Login = ()=> import('../components/Login')
// const Home = import('../components/Home') 也可以直接写过去

Vue.use(VueRouter)

const routes = [
  { path: "/", redirect: "/login" },
  { path: "/login", component: Login },     //懒加载
  { 
    path: "/home",
    component: () => import('../components/Home') ,
    redirect:"/welcome",
    children:[
      {path:"/welcome",component:()=>import("../components/view/Welcome")},
      {path:"/users",component:()=>import("../components/view/Users")},
    ]
  }
]



const router = new VueRouter({
  routes
})



//路由守卫
router.beforeEach((to,from,next)=>{
  //to将要访问的路径
  //from从那个路径来
  //next()放行函数 next('login')强制转跳

  if(to.path == '/login'){ //如果访问的是登陆页 直接放行
    return next();
  }
  //如果不是登陆页 获取token
  const tokenStr = window.sessionStorage.getItem('token');
  if(!tokenStr){ //没有token就去登陆页
    return next('/login');
  }
  //如果有token 直接放行
  next();

})



export default router



